package com.frxuexi.park2212.emp

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.frxuexi.lib_base.base.BaseActivity
import com.frxuexi.lib_base.entity.DepartBean
import com.frxuexi.lib_base.entity.DepartBeanItem
import com.frxuexi.lib_base.entity.DepartNumBean
import com.frxuexi.park2212.R
import com.frxuexi.park2212.databinding.ActivityEmpBinding
import dagger.hilt.android.AndroidEntryPoint

@Route(path = "/app/EmpActivity")
@AndroidEntryPoint
class EmpActivity : BaseActivity<ActivityEmpBinding,EmpViewModel>() {
    val empAdapter by lazy { EmpAdapter() }
    val departs= mutableListOf<DepartBeanItem>()
    var departNums= mutableListOf<DepartNumBean>()
    val empNumAdapter by lazy { EmpNumAdapter() }
    override fun initData() {
        vm.getEmps.observe(this){
            empAdapter.data.clear()
            empNumAdapter.data.clear()
            it.forEach {emp->
                departs.forEach {
                    if(it.id==emp.departmentId){
                        emp.departName=it.name
                    }
                }
            }
            empAdapter.addData(it)
            empAdapter.notifyDataSetChanged()

            //统计每个部门有多少人
            val map = empAdapter.data.groupBy {
                it.departName
            }
            departNums.clear()
            map.forEach { t, u ->
                departNums.add(DepartNumBean(t,u.size))
            }
            empNumAdapter.addData(departNums)
            empNumAdapter.notifyDataSetChanged()

        }

        vm.getDeparts.observe(this){
            departs.clear()
            departs.addAll(it)
            vm.getEmps()
        }
    }

    override fun initView() {
        binding.empRv.apply {
            adapter=empAdapter
            layoutManager=LinearLayoutManager(this@EmpActivity)
        }

        binding.empRvDepart.apply {
            adapter=empNumAdapter
            layoutManager=LinearLayoutManager(this@EmpActivity,RecyclerView.HORIZONTAL,false)
        }

        binding.headEmp.apply {
            headerBack.setOnClickListener {
                finish()
            }
            headerTitle.setText("人员管理")
            headerAdd.visibility=View.GONE
        }

        binding.btnAddemp.setOnClickListener {
            ARouter.getInstance().build("/app/EmpAddActivity").navigation()
        }

    }

    override fun onResume() {
        super.onResume()

        vm.getDeparts()
    }

}